<template>
    <div class="page-container">
        <el-backtop :right="100" :bottom="100" ref="refBackTop" :visibility-height="100" target=".el-main"></el-backtop>

        <!-- 头部 -->
        <div class="page-filter">
            <el-input v-model="inputUserName" placeholder="请输入管理员名称" clearable />
            <el-button type="primary" :icon="Search" @click="getAdminUserList">查找</el-button>
            <el-button type="primary" :icon="Plus" @click="handleOpenAddDialog" v-permission="'sys:admin:create'">添加</el-button>
        </div>
        <!-- 列表数据 -->
        <div class="page-table">
            <el-table :data="adminUserList" border style="width: 100%" stripe v-loading="loading" element-loading-text="拼命加载中...">
                <el-table-column prop="id" label="管理员ID" />
                <el-table-column prop="username" label="管理员名称" />
                <el-table-column prop="realname" label="真实姓名" />
                <el-table-column prop="phone" label="电话" />
                <el-table-column label="管理员角色" prop="rolelist">
                    <template #default="scope">
                        <template v-for="item in scope.row.rolelist" :key="item">
                            <div>
                                <el-tag>{{ item }}</el-tag>
                            </div>
                        </template>

                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleOpenEditDialog(scope.row)" v-permission="'sys:admin:edit'">修改</el-button>
                        <el-button type="danger" size="small" v-permission="'sys:admin:delete'">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页 -->
        <div style="overflow: hidden;">
            <Pagination v-bind="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
        <!-- 添加修改对话框 -->
        <el-dialog v-model="dialogFormVisible" :title="title" @close="handleCloseDialog">
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="ruleForm.username" :disabled="title==='修改'?true:false"/>
                </el-form-item>
                <el-form-item label="密码" prop="password" v-if="title === '添加'">
                    <el-input v-model="ruleForm.password" />
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="ruleForm.phone" />
                </el-form-item>
                <el-form-item label="真实姓名" prop="realname">
                    <el-input v-model="ruleForm.realname" />
                </el-form-item>
                <el-form-item label="角色">
                    <el-select v-model="ruleForm.roleIds" multiple placeholder="请选择角色" style="width: 240px">
                        <el-option v-for="item in enumRoleList" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                        {{ title }}
                    </el-button>
                    <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { post } from '@/utils/http';
import { Plus, Search } from '@element-plus/icons-vue';
import { ElMessage,ElBacktop } from 'element-plus';
import { nextTick, onMounted, reactive, ref } from 'vue';
import Pagination from '@/components/pagination/Pagination.vue';
import {ClassPagination} from '#/index'
import type { FormInstance, FormRules } from 'element-plus'

//返回顶部节点
const refBackTop = ref()
//显示是否加载
const loading = ref(false)
//搜索框绑定的数据
const inputUserName = ref('')
//分页对象
const pagination:ClassPagination = reactive(new ClassPagination())
//管理员列表
const adminUserList = ref([{} as AdminUser])
//枚举角色列表
const enumRoleList = ref([{} as Enumeration])
//是否显示对话框
const dialogFormVisible = ref(false)
//对话框主题
const title = ref('')
//form表单节点
const ruleFormRef = ref<FormInstance>()
//form表单对象
const ruleForm = reactive({
    username: '',
    password: '',
    phone: '',
    realname: '',
    roleIds: []
})
/**
 * 校验手机号格式
 * @param rule 规则
 * @param value 相对应的值
 * @param callback 回调函数
 */
// const validatePhone = (rule: any, value: any, callback: any) => {
//     let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
//     if (!reg.test(value)) {
//         callback(new Error('请输入正确的手机号码格式'))
//     } else {
//         callback()
//     }
// }
//校验规则
const rules = reactive<FormRules>({
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    phone: [{ required: true, pattern:/^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            message:'请正确填写你的号码', trigger: 'blur' }],
    realname: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }]
})

/**
 * 生命周期请求数据
 */
onMounted(() => {
    getAdminUserList()
})
/**
 * 请求管理员列表
 */
function getAdminUserList() {
    loading.value = true
    const data = { _gp: 'admin', _mt: 'list', page: pagination.currentPage, limit: pagination.pageSize,username:inputUserName.value }
    post(data).then(res => {
        const { data, errmsg, errno } = res
        console.log(res)
        if (200 === errno && "成功" === errmsg) {
            pagination.total = data.total
            return Promise.resolve(data.items)
        } else {
            ElMessage.error(errmsg)
        }
    }).then(res => {
        //筛选出对应的角色
        let roleArr: Enumeration[] = [];
        const data = { _gp: 'admin.role', _mt: 'options' }
        post(data).then(respone => {
            roleArr = [...respone.data]
            enumRoleList.value = respone.data
            console.log(res);
            res.forEach((element: { roleIds: number[]; rolelist: string[]; }) => {
                element.rolelist = []
                if (element.roleIds) {
                    element.roleIds.forEach(item => {
                        roleArr.forEach(data => {
                            if (data.value === item) {
                                element.rolelist.push(data.label)
                            }
                        })
                    })
                }
            });
            adminUserList.value = res
            nextTick(() => {
                loading.value = false
                refBackTop.value.$el.click?.()
            })
        })

    })
}
/**
 * 改变一页多少行,防止多次请求
 * @param value 一页多少行
 */
function handleSizeChange(value: number) {
    let tempCurrent = Math.ceil(pagination.total / value)
    if (tempCurrent < pagination.currentPage) {
        pagination.currentPage = tempCurrent
    }
    pagination.pageSize = value
    getAdminUserList()
}

/**
 * 改变当前页
 * @param value 当前页数
 */
function handleCurrentChange(value: number) {
    pagination.currentPage = value
    getAdminUserList()
}
/**
 * 临时存储对象，用于重置
 */
let tempObj = {
    username: '',
    realname: '',
    phone: '',
    roleIds: []
};
/**
 * 打开添加对话框
 */
function handleOpenAddDialog() {
    dialogFormVisible.value = true
    title.value = '添加'
    Object.assign(tempObj, ruleForm)
}

/**
 * 打开修改对话框
 * @param row 当前行对象
 */
function handleOpenEditDialog(row: AdminUser) {
    dialogFormVisible.value = true
    title.value = '修改'
    Object.assign(ruleForm, row)
    Object.assign(tempObj, ruleForm)
}
/**
 * 添加修改确定按钮
 * @param formEl form表单节点
 */
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            let mt = title.value === "添加" ? 'create' : 'edit'
            const data = { _gp: 'admin', _mt: mt, adminDTO: JSON.stringify(ruleForm) }
            post(data).then(res => {
                const { data, errmsg, errno } = res
                if (200 === errno) {
                    ElMessage.success(title.value + '成功')
                    //关闭对话框刷新页面
                    dialogFormVisible.value = false
                    getAdminUserList()
                } else {
                    ElMessage.error(errmsg)
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
/**
 * 关闭对话框的回调函数，清除表单及清空ruleForm对象
 */
function handleCloseDialog() {
    ruleFormRef.value?.resetFields()
    ruleForm.password = ""
    ruleForm.phone = ""
    ruleForm.realname = ""
    ruleForm.roleIds = []
    ruleForm.username = ""
}
/**
 * 重置表单
 * @param formEl form表单节点
 */
function resetForm(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.resetFields()
    Object.assign(ruleForm, tempObj)

}
</script>
<style lang="less" scoped>
.page-filter {
    height: 100%;
    overflow-x: hidden;

    &>.el-input {
        width: 200px;
        margin-right: 5px;
    }
}
</style>